<template>
    <div class="teamuserdata" v-loading="loading">
        <!-- <div class="myRow"> -->
        <div class="col" title="该数据统计时间范围内团队成员的公开题库历史提交测评数，【包括】团队创建前的评测提交">
            <div class="char">
                <vLine :option="assessmentSubmit"></vLine>
            </div>
        </div>
        <div class="col" title="该数据统计时间范围内所有成员的公开题库评测情况">
            <div class="char">
                <!-- :height="'500px'" -->
                <vLine :option="acQuestion" :height="'500px'"></vLine>
            </div>
        </div>
        <!-- </div> -->
        <!-- <div class="myRow"> -->
        <div class="col" title="该数据统计时间范围内团队成员的公开题库全AC题目标签分布">
            <div class="char">
                <vPie :option="acQuestionLabel"></vPie>
            </div>
        </div>
        <div class="col" title="该数据统计时间范围内团队成员的历史提交评测时间分布，【包括】团队创建前的评测提交">
            <div class="char ">
                <vBar :option="assessmentTime"></vBar>
            </div>
        </div>
        <!-- </div> -->
    </div>
</template>

<script setup lang="ts">
import moment from 'moment'
import { debounce } from 'underscore'
import { computed, onMounted, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { asyncranking, asyncselectchart, asyncselectteamselectuser, asyncteamuserquestion } from '../../../api'
import { Storekey } from '../../../interface'
import FetchApi, { logdata } from '../../../logs/api'
import Studycodemodel from '../../../mysql_interface/studycodemodel'
import vBar from '../../components/vCharts/bar.vue'
import vLine from '../../components/vCharts/line.vue'
import vPie from '../../components/vCharts/pie.vue'
import icon from '../../img/chart-icon.png'


const store = useStore(Storekey)
const prop = defineProps<{ formdata: { showTeamData: boolean, userId?: number, times: [string, string] } }>()

const dfl = ref(0)
const loading = ref(false)
const ACrank = ref(0)
// 当前登录用户
const user = computed(() => {
    return store.state.user;
});
const teamid = computed(() => {
    return user.value?.teamid;
});
const label = computed(() => {
    return store.state.label?.rows || []
})

const debounce1 = debounce(start, 100)
const isFirstLoad = ref(true);  // 初始化标志变量为 true
onMounted(() => {
    console.log("in onMounted formdata", prop.formdata)
    isFirstLoad.value = false;
    if (prop.formdata?.showTeamData) {
        debounce1()
    }
})
// 监听团队切换
watch(() => teamid.value, (o, n) => {
    if (o !== n) start();
})
watch(() => prop.formdata, (e) => {
    if (isFirstLoad.value) return;  // 如果是首次加载，直接返回
    console.log("in watch formdata", e)
    debounce1()
}, { deep: true })

// 评测提交次数
const assessmentSubmit = ref({
    height: 200,
    // width: '100%',
    title: {
        text: "{icon|} 评测提交次数", left: "0",
        textStyle: {
            fontSize: 14,
            rich: {
                icon: {
                    backgroundColor: {
                        image: icon //'../../img/chart-icon.png'
                    },
                    height: 14,
                }
            },
        },
    },
    tooltip: {
        trigger: "axis",
        axisPointer: {
            type: "shadow"
        }
    },
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            type: 'line',
            name: "评测数",
            // smooth: true,
            data: [],
        }
    ]
})
// 全AC题目数(成员)
const acQuestion = ref({
    height: 'auto',
    title: {
        text: "{icon|} 成员全AC题目数", left: '0',
        textStyle: {
            fontSize: 14,
            rich: {
                icon: {
                    backgroundColor: {
                        image: icon //'../../img/chart-icon.png'
                    },
                    height: 14,
                }
            },
        },
    },
    dataZoom: [{ type: "inside" },],
    tooltip: {
        trigger: "axis", axisPointer: { type: "shadow" },

    },
    legend: { type: 'scroll', top: '35', },
    grid: { // 直角坐标系内绘图网格
        // show:true, // 是否显示直角坐标系网格。[ default: false ]
        left: "15%", // grid 组件离容器左侧的距离。
        top: "15%",
        bottom: "35%", // 增加底部空间 
        // right:"30px",
    },
    xAxis: {
        // type: "value"
        // 纵向
        type: 'category',
        data: [],
        axisLabel: {
            show: true,
            interval: 0,
            // rotate: 60, // 斜角显示标签
            fontSize: 12,
            formatter: function (val: string) {
                if (val.length > 10) { // 如果标签长度大于10，进行截断
                    val = val.substring(0, 10) + '...';
                }
                return val.split("").join("\n"); // 竖排显示
            }
        },
    },
    yAxis: { type: 'value' }, // 纵向
    // yAxis: {
    //     type: 'category',
    //     data: [],
    //     axisLabel: {
    //         formatter: function (val) {
    //             if (val.length > 4) {
    //                 return val.substring(0, 4) + '…';
    //             } else {
    //                 return val;
    //             }
    //         }
    //     }
    // },
    series: [
        { type: 'bar', name: "评测题目数", data: [], top: '100' },
        { type: 'bar', name: "全AC题目数", data: [], top: '100' },
        // { type: 'line', name: "全AC题目数", data: [], },
        // { type: 'line', name: "评测题目数", data: [], },
        // { type: 'line', name: "测试点得分率", smooth: true, data: [], },
    ]
})
// 动态计算图表高度函数
const calculateChartHeight = (data: string[]) => {
    const baseHeight = 400; // 基础高度
    const extraHeightPerLine = 20; // 每行额外高度
    const numberOfLines = Math.ceil(Math.max(...data.map(item => item.length)) / 10); // 计算最长标签行数
    return baseHeight + (extraHeightPerLine * numberOfLines);
};
// 设置动态高度
const updateChartData = (data: string[]) => {
    console.log(data, calculateChartHeight(data))
    acQuestion.value.height = calculateChartHeight(data);
}
// 全AC题目标签
const acQuestionLabel = ref({
    height: 500,
    title: {
        text: '{icon|} 全AC题目标签', left: '0', top: '30',
        textStyle: {
            fontSize: 14,
            rich: {
                icon: {
                    backgroundColor: {
                        image: icon //'../../img/chart-icon.png'
                    },
                    height: 14,
                }
            },
        }
    },
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)' },
    legend: {
        orient: 'horizontal', bottom: '20', icon: "roundRect", itemGap: 5,
        type: 'scroll',
        selected: {},
    },
    series: [
        {
            name: "标签",
            type: 'pie',
            radius: '60%',
            center: ['50%', '50%'],
            // roseType: 'area',
            itemStyle: {
                // borderRadius: 8
            },
            data: [],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
})
// 评测时间分布
const assessmentTime = ref({
    height: 200,
    title: {
        text: "{icon|} 评测时间分布", left: "0",
        textStyle: {
            fontSize: 14,
            rich: {
                icon: {
                    backgroundColor: {
                        image: icon //'../../img/chart-icon.png'
                    },
                    height: 14,
                }
            },
        },
    },
    tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        formatter: (params) => {
            let v = params[0] || {}
            let from = Number(v?.name.substring(0, v?.name.length - 1))
            let to = from + 1
            return `<div>
        <div>${from} - ${to}点</div>
        <span >${v?.seriesName}</span>
        <span style="font-weight: bold">${v?.data}</span>
      </div>`;
        },
    },
    dataZoom: [{ type: "inside" }],
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: { type: 'value', },
    series: [
        {
            name: "提交评测数",
            type: 'bar',
            data: [],
        }
    ],
})
// 测试点评测概况
const assessmentCase = ref<{ name: string, count: number, }[]>([])
// 全评测题目标签
const questionLabel = ref<{ name: string, count: number, }[]>([])
// 团队观看视频数
const watchVideo = ref<{ name: string, count: number }[]>([])

async function start() {
    const { userId, times = [] } = prop.formdata;
    const formdata = {
        teamid: teamid.value,
        userid: userId || undefined,
    }
    if (times[0] && times[1]) {
        formdata.formdate = new Date(times[0])
        formdata.todate = new Date(times[1])
    }
    if (teamid.value) {
        loading.value = true
        const teamUserQRet = await asyncteamuserquestion(formdata) // teamuserquestion
        // 全AC题目标签
        const acQuestionLabelData = []
        const selected = {}
        const limitCount = 20
        teamUserQRet.Alllabel.sort((a, b) => b.count - a.count).forEach<{ name: string, count: number, }>((e, k) => {
            let labelName = label.value.find(t => t.ID === e.labelid)?.name as string
            // if (k < limitCount) {
            //    let other =  acQuestionLabelData[limitCount] || { name: '其他', value: e.count,}
            //     other.value += e.count
            //     acQuestionLabelData[limitCount] = other
            // } else {
            acQuestionLabelData.push({ name: labelName, value: e.count, })
            // 
            selected[labelName] = k < limitCount
            // }
        })
        acQuestionLabel.value.series[0].data = acQuestionLabelData
        acQuestionLabel.value.legend.selected = selected

        // 全评测题目标签
        questionLabel.value = teamUserQRet.Alllabel.sort((a, b) => b.count - a.count).map<{ name: string; count: number, color: string }>((e, k) => {
            return {
                name: label.value.find(t => t.ID === e.labelid)?.name as string,
                count: e.count,
            }
        })
        let timetype: 'w' | 'm' = 'w'
        let _tmp = 0
        let _all = 0
        ACrank.value = teamUserQRet.ACrank + teamUserQRet.ACmatch
        const _tmparr: Array<Studycodemodel.Iuserquestion | Studycodemodel.Imatchuserquestion> = []
        teamUserQRet.userquestion.forEach(f => {
            const count = f.resultdataarr?.filter(e => e === 'AC').length || 0
            const _e = _tmparr.findIndex(n => n.questionid === f.questionid)
            if (_e === -1) {
                _tmparr.push(f)
            } else {
                const _count = _tmparr[_e].resultdataarr?.filter(e => e === 'AC').length
                if (_count ? _count : 0 < count) {
                    _tmparr[_e] = f
                }
            }
            _all = _all + Number(f.resultdataarr?.length || 0)
            _tmp = _tmp + Number(f.resultdataarr?.filter(e => e === 'AC').length || 0)
        })
        teamUserQRet.matchquestion.forEach(f => {
            const count = f.resultdataarr?.filter(e => e === 'AC').length || 0
            const _e = _tmparr.findIndex(n => n.questionid === f.questionid)
            if (_e === -1) {
                _tmparr.push(f)
            } else {
                const _count = _tmparr[_e].resultdataarr?.filter(e => e === 'AC').length
                if (_count ? _count : 0 < count) {
                    _tmparr[_e] = f
                }
            }
            _all = _all + Number(f.resultdataarr?.length || 0)
            _tmp = _tmp + Number(f.resultdataarr?.filter(e => e === 'AC').length || 0)
        })
        // 测试点评测概况 ac 占比
        assessmentCase.value = teamUserQRet.allrank ? [{ name: 'AC测试点', count: _tmp, }, { name: '非AC测试点', count: _all - _tmp, }] : []
        // 得分占比
        dfl.value = Math.floor(_tmp / _all * 100)
        // const num = new Date(times[1]).getTime() - new Date(times[0]).getTime()
        // const n = num / 1000 / 60 / 60 / 24 / 7
        timetype = 'm'
        // if (n > 14) {
        //     timetype = 'm'
        // } else {
        //     timetype = 'w'
        // }

        // 评测时间分布
        let assessmentTimeXData = [] // assessmentTime.value.xAxis?.data
        let assessmentTimeYData = []
        Array.from({ length: 24 }).forEach((v, k) => {
            const z = teamUserQRet.groupkuserquestion.find(f => f.hover == k)
            assessmentTimeXData.push(k + '点')
            if (z) {
                assessmentTimeYData.push(z.count)
            } else {
                assessmentTimeYData.push(0)
            }
        })
        assessmentTime.value.xAxis.data = assessmentTimeXData
        assessmentTime.value.series[0].data = assessmentTimeYData

        // 评测提交次数
        let cond = {
            teamid: teamid.value,
            timetype: '%Y-%m', // timetype === 'w' ? '%Y-%v周' : 
            userids: userId ? [userId] : undefined
        }
        if (times[0] && times[1]) {
            cond.starttime = new Date(times[0])
            cond.endtime = new Date(times[1])
        }
        asyncselectchart(cond).then(f => {
            let assessmentSubmitXData = []
            let assessmentSubmitYData = []
            f.userquestion.forEach(e => {
                // 调整日期格式
                const day = moment(e.day).format('YY-MM')
                assessmentSubmitXData.push(day)
                assessmentSubmitYData.push(e.count)
            })
            assessmentSubmit.value.xAxis.data = assessmentSubmitXData
            assessmentSubmit.value.series[0].data = assessmentSubmitYData
        })

        // 成员全AC题目数
        const payload = {
            // questionbankid:  ,
            teamid: teamid.value,
            userid: userId || undefined,
        }
        if (times[0] && times[1]) {
            payload.formdate = new Date(times[0])
            payload.todate = new Date(times[1])
        }
        const ret = await asyncranking(payload)

        const rankLimit = 10;
        const ACrankSorted = ret.ACrank.sort((a, b) => (b.count || 0) - (a.count || 0)).slice(0, rankLimit)
        let acQuestionXData = []
        let acQuestionYData = []
        let assessmentQuestionYData = []
        // let caseScoreRateYData = []
        ACrankSorted.forEach(e => {
            const data = ret.user.find(v => e.userid === v.ID)
            let name = data.name
            let ACcount = e?.count || 0 // 全AC题目数
            let assessmentQuestion = e?.distinctquestionid || 0 // 评测题目数
            // 测试点得分率
            // let caseScoreRate = (Math.floor(Number(e?.resultdataarrlength || 0) / Number(e?.resultdataarraclength || 0) * 100) || 0) + '%'
            // caseScoreRateYData.push(caseScoreRate)
            acQuestionXData.push(name)
            acQuestionYData.push(ACcount)
            assessmentQuestionYData.push(assessmentQuestion)
        })
        // acQuestion.value.yAxis.data = acQuestionXData // 横向
        acQuestion.value.xAxis.data = acQuestionXData // 纵向
        acQuestion.value.series[0].data = assessmentQuestionYData
        acQuestion.value.series[1].data = acQuestionYData
        // acQuestion.value.series[2].data = caseScoreRateYData

        // 设置动态高度
        // updateChartData();

        // 观看视频
        watchvideo(timetype).then(({ data }) => {
            watchVideo.value = data.map((e: { count: number, day: string }) => {
                return {
                    name: `${e.day}${timetype === 'm' ? '月' : '周'}`,
                    count: Number(e.count)
                }
            })
        }).catch(console.error)

        loading.value = false
    }

    async function watchvideo(timetype: string) {
        const formInline: logdata = {
            query: "* | with_pack_meta",
            line: 99,
            offset: 0,
            projectName: "htetest1",
            logstoreName: "ojhte",
            from: new Date(times[0]),
            to: new Date(times[1]),
            reverse: true,
        };
        if (times[0] && times[1]) {
            formInline.from = new Date(times[0])
            formInline.to = new Date(times[1])
        }
        let str = ''
        if (userId) {
            const [user] = await asyncselectteamselectuser({ teamid: teamid.value, userid: userId, phonenum: true, gid: true })
            if (user.user?.phonenum) {
                str = `and _phonenum_:${user.user?.phonenum}`
            } else {
                str = `and _cid_:${user.user?.gid}`
            }
        }
        // const query = `* and type:video and _teamids_:${prop.data.ID} ${str} | select  ${timetype === 'm' ? 'month' : 'week'}(from_unixtime(__time__)) as day, count(__time__) as count group by day order by day`;
        const query = `* and type:video and _teamids_:${teamid.value} ${str} | select  date_format(date_trunc( '${timetype === 'm' ? 'month' : 'week'}',__time__), '${timetype === 'm' ? '%Y-%m' : '%Y-%v'}') as day, count(__time__) as count group by day order by day`;
        return FetchApi(
            Object.assign({}, formInline, {
                query,
            })
        );
    }
}
</script>

<style scoped>
.char {
    padding-top: var(--container-margin);
    color: var(--color-43);
    text-align: center;
}

.teamuserdata {
    /* padding: 10px 14px 0 0; */
}

header {
    font-size: 16px;
    margin-bottom: 12px;
}
</style>
